package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class MobileLoginController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;

    /**
     *
     * 手机端登录保存用户功能
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/smsLogin")
    public Result smslogin(@RequestBody Map map, HttpSession session){
        //获取前端缓过来的电话号和验证码
        String telephone = (String) map.get("telephone");
        String validateCode = map.get("validateCode").toString();
        String key = "MOBILE_SIGNIN_"+telephone;
        //在redis中取出存入的验证码
        Object code = redisTemplate.opsForValue().get(key);
        //对比验证码
        boolean equals = code.toString().equals(validateCode);
        //判断验证码登录
        if (equals){
            //登陆成功，删除redis中的验证码
            redisTemplate.delete(key);
            //查询数据库中有没有当前用户
            Member member = memberService.getUser(telephone);
            //如果没有就添加到数据库
            if (member == null ){
                member = new Member();
                member.setPhoneNumber(telephone);
                memberService.saveUser(member);
            }
            //把当前用户的id存到session中
            session.setAttribute("member",member.getId());
            //返回登录成功
            return new Result(true,MessageConst.ACTION_SUCCESS,null);
            }
        //判断验证码错误，返回登录失败
        return new Result(false,MessageConst.LOGIN_FAIL,null);
    }
}
